package com.innovation.ic.cyz.base.service.cyz.impl;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.cyz.base.model.cyz.Carousel;
import com.innovation.ic.cyz.base.pojo.constant.RedisStorage;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.service.cyz.CarouselService;
import com.innovation.ic.cyz.base.service.cyz.DataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author linuo
 * @desc DataService的具体实现类
 * @time 2022年6月17日09:21:18
 */
@Service
@Transactional
public class DataServiceImpl implements DataService {
    private static final Logger log = LoggerFactory.getLogger(DataServiceImpl.class);

    @Resource
    private ServiceHelper serviceHelper;
    @Resource
    private CarouselService carouselService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据redis的key删除对应数据
     *
     * @param redisKey
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delRedisDataByKey(String redisKey) {
        ServiceResult<Boolean> returnResult = new ServiceResult<>();
        log.info("删除redis中[{}]开头的数据", redisKey);
        Set<String> keySet = serviceHelper.getRedisManager().keysPrefix(redisKey);
        serviceHelper.getRedisManager().del(keySet);

        returnResult.setMessage(ServiceResult.DELETE_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 将carousel表中的数据导入redis
     *
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<Boolean> importCarouselIntoRedis() {
        ServiceResult<Boolean> returnResult = new ServiceResult<>();
        //获取轮播图所有数据
        ServiceResult<List<Carousel>> carouselList = carouselService.findCarouselListData();

        List<Carousel> result = carouselList.getResult();
        if (result != null && result.size() > 0) {
            String[] resultSize = new String[result.size()];
            for (int i = 0; i < result.size(); i++) {
                String resultData = JSON.toJSONString(result.get(i));
                resultSize[i] = resultData;
            }
            stringRedisTemplate.opsForList().leftPushAll(RedisStorage.BANNER_CAROUSEL_PREFIX, resultSize);
        } else {
            return null;
        }
        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }
}